package com.ruoyi.wss;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 服务启动后，把 Redis 中留存的上次连接信息
 * 1. 重新加载到内存索引
 * 2. 向这些 platformId 推送 "restart" 消息，让终端感知并重新建链
 */
@Component
public class ConnectionRecover implements ApplicationRunner {

    private static final String REDIS_KEY = "parking:conn";
    private static final Logger log = LoggerFactory.getLogger(ConnectionRecover.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void run(ApplicationArguments args) {
        Map<Object, Object> all = redisTemplate.opsForHash().entries(REDIS_KEY);
        if (all.isEmpty()) return;

        all.keySet().forEach(platformId -> {
            // 通知终端：服务端已重启
            // 由于旧 session 已失效，这里仅做日志，真正重连由终端发起
            System.err.println("[RECOVER] 发现设备 " + platformId + " 需要重连");
            log.info("[RECOVER] 发现设备 {} 需要重连", platformId);
            // TODO: 如果终端支持 HTTP 回调，可在这里调用其重连接口
        });
    }
}
